package com.laolang.shop.common.data.mvc.interceptor;

import cn.hutool.core.util.StrUtil;
import com.laolang.shop.common.core.consts.ModuleNameConst;
import com.laolang.shop.common.core.util.LogUtil;
import com.laolang.shop.common.data.mvc.threadlocal.TraceRequestHolder;
import com.laolang.shop.common.data.mvc.trace.TraceComponent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

/**
 * mvc 全局拦截器 <br />
 * <ul>
 *     <li>全局流水号</li>
 *     <li>khl 请求耗时</li>
 *     <li>khl 打印输入输出</li>
 * </ul>
 *
 * @author khlbat
 * @version 1.0
 * @date 2020/11/1 20:46
 */
@Slf4j
@Component
public class TraceInterceptor implements HandlerInterceptor {

    @Autowired
    private TraceComponent traceComponent;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        TraceRequestHolder.set(traceComponent.getNextTraceId(uri, LocalDateTime.now()));
        LogUtil.info(log, ModuleNameConst.APP, StrUtil.format("traceId:{} request-begin:{}", TraceRequestHolder.get(), uri));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LogUtil.info(log, ModuleNameConst.APP, StrUtil.format("traceId:{} request-end:{}", TraceRequestHolder.get(), request.getRequestURI()));
    }
}
